<script setup lang="ts">
import { computed, nextTick, reactive, watch } from 'vue';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { addAnalogDevice, addDigitalDevice } from '@/service/api/businessApi';
import { useProjectStore } from '@/store/modules/project';
import { deviceTypeEnum } from '@/enum';
const projectStore = useProjectStore();

defineOptions({
  name: 'TerminalOperateDrawer'
});

interface Props {
  operateType: AntDesign.TableOperateType;
  rowData?: any | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
  (e: 'changeDeviceType', deviceType: any): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, resetFields } = useAntdForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<AntDesign.TableOperateType, string> = {
    add: '新增设备',
    edit: '编辑设备',
    addChild: '新增子设备'
  };
  return titles[props.operateType];
});

const model: any = reactive(createDefaultModel());
const hostData = defineModel<any>('hostData', { required: true });
const deviceCategoryList = defineModel<any>('deviceCategoryList', { required: true });
const farmData = defineModel<any>('farmData', { required: true });

function createDefaultModel(): any {
  return {};
}

const rules: any = {
  deviceNo: defaultRequiredRule,
  deviceType: defaultRequiredRule,
  categoryCode: defaultRequiredRule,
  nodeName: defaultRequiredRule,
  channel: defaultRequiredRule,
  farmId: defaultRequiredRule
};

/** the enabled role options */
async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if ((props.operateType === 'edit' || props.operateType === 'addChild') && props.rowData) {
    await nextTick();
    const data = {
      ...props.rowData,
      categoryCode: props.rowData.categoryCode && String(props.rowData.categoryCode)
    };
    Object.assign(model, data);
  }
}

function closeDrawer() {
  visible.value = false;
}

const nodeNoChange = (val: any) => {
  const data = hostData.value.find((item: any) => item.hostNo === val);
  model.hostId = data.id;
  model.collectionName = data.collectionName;
};

const doAddSubmit = async () => {
  if(model.deviceType === 1) {
    // 新增传感器
    const res = await addAnalogDevice({
      parentId: 0,
      ...model,
      projectId: projectStore.currentProject?.id,
    });
    if (res.error === null) {
      window.$message?.success('新增（传感器）成功');
      closeDrawer();
      emit('submitted');
    }
  } else {
    // 新增控制器
    const res = await addDigitalDevice({
      parentId: 0,
      ...model,
      projectId: projectStore.currentProject?.id,
      status: ''
    });
    if (res.error === null) {
      window.$message?.success('新增（控制器）成功');
      closeDrawer();
      emit('submitted');
    }
  };
};

async function handleSubmit() {
  await validate();
  if (props.operateType === 'add' || props.operateType === 'addChild') {
    await doAddSubmit();
  }
}

const deviceTypeChange = (val: any) => {
  emit('changeDeviceType', val);
};

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    resetFields();
  }
});
</script>

<template>
  <AModal v-model:open="visible" :title="title" :width="560" :maskClosable="false">
    <AForm
      ref="formRef"
      :model="model"
      :rules="rules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      style="margin-top: 40px"
    >
      <AFormItem label="设备编码" name="deviceNo">
        <AInput v-model:value="model.deviceNo" placeholder="请输入设备编码" />
      </AFormItem>
      <AFormItem label="设备名称" name="deviceName">
        <AInput v-model:value="model.deviceName" placeholder="请输入设备名称" />
      </AFormItem>
      <AFormItem label="设备类型" name="deviceType">
        <ASelect
          v-model:value="model.deviceType"
          placeholder="请选择设备类型"
          :options="deviceTypeEnum"
          clearable
          @change="deviceTypeChange"
        />
      </AFormItem>
      <AFormItem label="设备分类" name="categoryCode">
        <ASelect
          v-model:value="model.categoryCode"
          placeholder="请选择设备分类"
          :options="deviceCategoryList"
          :field-names="{ label: 'categoryName', value: 'categoryCode', options: 'options' }"
          clearable
        />
      </AFormItem>
      <AFormItem v-if="model.parentId === undefined" label="终端名称" name="hostNo">
        <ASelect
          v-model:value="model.hostNo"
          placeholder="请选择终端名称"
          :options="hostData"
          :field-names="{ label: 'hostName', value: 'hostNo', options: 'options' }"
          clearable
          @change="nodeNoChange"
        />
      </AFormItem>
      <AFormItem label="通道" name="channel">
        <AInput v-model:value="model.channel" placeholder="请输入通道" />
      </AFormItem>
      <template v-if="model.deviceType === 1">
        <AFormItem label="单位" name="unit">
          <AInput v-model:value="model.unit" placeholder="请输入单位" />
        </AFormItem>
        <AFormItem v-if="model.categoryCode !== '1000'" label="告警下限" name="lowAlarm">
          <AInput v-model:value="model.lowAlarm" placeholder="请输入告警下限" />
        </AFormItem>
        <AFormItem v-if="model.categoryCode !== '1000'" label="告警上限" name="hiAlarm">
          <AInput v-model:value="model.hiAlarm" placeholder="请输入告警上限" />
        </AFormItem>
      </template>
        <AFormItem label="养殖池" name="farmId">
            <ASelect
                v-model:value="model.farmId"
                placeholder="请选择养殖池"
                :options="farmData"
                :field-names="{ label: 'name', value: 'id', options: 'options' }"
            />
        </AFormItem>
      <AFormItem label="备注" name="remark">
        <ATextarea v-model:value="model.remark" placeholder="请输入备注" />
      </AFormItem>
    </AForm>
    <template #footer>
      <ASpace :size="16">
        <AButton @click="closeDrawer">取消</AButton>
        <AButton type="primary" @click="handleSubmit">确认</AButton>
      </ASpace>
    </template>
  </AModal>
</template>

<style scoped></style>
